package klg.common.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class FileTools {
	public static void saveObject(String filename,Object obj) throws IOException{
		File f = new File(filename);
		if (!f.exists()) {
				f.createNewFile();
		}
		FileOutputStream fos = new FileOutputStream(f);
		ObjectOutputStream oos = new ObjectOutputStream(fos);
		oos.writeObject(obj);
		fos.close();
		oos.close();
	}
	public static Object readObject(String filename) throws IOException, ClassNotFoundException {
		Object obj=null;
		File ft = new File(filename);
		if (ft.exists()) {
			 FileInputStream fis= new FileInputStream(ft); 
			ObjectInputStream ois= new ObjectInputStream(fis);
				obj=ois.readObject();
				fis.close();
				ois.close();
		} else {
		//do something
		}
		return obj;
	}
	
	/**
	 * 文件查找
	 * @param srcFile
	 * @param fileNameRegex 正则表达式。
	 * @return
	 */
	public static List<File> searchFileName(File srcFile,String fileNameRegex){
		List<File> target=new ArrayList();
		if(!srcFile.isDirectory())
			return target;

		File[] files=srcFile.listFiles();
		for(File file:files){
			if(file.getName().matches(fileNameRegex))
				target.add(file);
		}
		return target;
	}
	/**
	 * 取得文件的后缀名
	 * @param file
	 * @return 不带"."的后缀名
	 */
	
	public static String getSuffix(File file){
		String name=file.getName();
		if(name.contains(".")){
			return name.substring(name.lastIndexOf(".")+1, name.length());
		}else
			return "";			
	}
	public static String createUUIDName(File file){
		return UUID.randomUUID().toString()+"."+getSuffix(file);
	}
	
	/**
	 * 从一个文件路径获取InputStream
	 * @param path
	 * @return
	 * @throws FileNotFoundException
	 */
	public static InputStream getInputStream(String path) throws FileNotFoundException{
		File file=new File(path);
		if(!file.exists())
			return null;
		return new FileInputStream(file); 
	}
	public static String makeDir(String dir){
		File file=new File(dir);
		if(!file.exists())
			file.mkdirs();
		return dir;
	}
	
	public static String newFIle(String path) throws IOException{
		File file=new File(path);
		if(!file.exists())
			file.createNewFile();
		return path;
	}
	
}
